import React, { Component, Fragment } from "react";
// antd
import { Table, Button, Col, Pagination, Form, Select, Tag, Input, Space, notification, Typography } from "antd";
// http
import http from '../../../utils/request';
import Action from "@c/buttonAction/Index";
import {CopyToClipboard} from 'react-copy-to-clipboard';

import { CopyOutlined, CheckOutlined } from '@ant-design/icons';

const { Text } = Typography;
const { Option } = Select;

class Ssl extends Component {
    constructor(props){
        super(props)
        this.state = {
            loading: false,

            // 分页
            total: '',
            page: 1,
            page_number: 10,

            // 搜索
            search_instance_platform: null,
            search_instance_account_name: null,
            search_domain_name: null,
            search_option_account: [],
            search_option_platform: [],
            aaa: [],

            // 表格
            dataSource: [],
            columns: [
                {title: "实例ID/名称", dataIndex: "instance_id", key: "instance_id",
                    render: (text, rowData) => {
                        return(
                            <Space direction="vertical">
                                <CopyToClipboard text={rowData.instance_id} 
                                    onCopy={() => 
                                        this.setState({copied: true},
                                        notification.open({
                                            message: '已复制到剪贴板',
                                            icon: <CheckOutlined style={{ color: 'green' }} />,
                                            duration: 2,
                                            placement: 'top',
                                        })
                                    )}
                                >
                                    <span><span style={{marginRight: "5px"}}><CopyOutlined /></span><span style={{color: "#6587FF"}}>{rowData.instance_id}</span></span>
                                </CopyToClipboard>
                                 
                                <Text >{rowData.domain_name}</Text>
                            </Space>
                        )
                    }
                },
                {title: "云平台", dataIndex: "platform", key: "platform",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.platform}-{rowData.account_name}</Tag>                                
                            </div>
                        )
                    }
                },
                {title: "状态", dataIndex: "status", key: "status"},
                {title: "ISSUE", dataIndex: "issue", key: "issue"},
                {title: "上传", dataIndex: "upload", key: "upload"},
                {title: "FQDN", dataIndex: "domain_name_full", key: "domain_name_full"},
                {title: "付费类型", dataIndex: "charge_type", key: "charge_type",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="magenta">{rowData.charge_type}</Tag>
                            </div>
                        )
                    }
                },
                {title: "创建时间", dataIndex: "create_time", key: "create_time"},
                {title: "过期时间", dataIndex: "expire_time", key: "expire_time"},
                {title: "操作", dataIndex: "operation", key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onexportExcelBtn(rowData)}>导出证书</Action.Button>
                                </Action>
                            </div>
                        )
                    }           
                }
            ],
        }
    }

    componentDidMount() {
        this.loadData()
        this.loadDataPlatform()
    }

    loadDataPlatform = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=>{
            const search_option_platform = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_platform.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                search_option_platform: search_option_platform
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'platform': this.state.search_instance_platform,
            'account_name': this.state.search_instance_account_name,
            'domain_name__contains': this.state.search_domain_name,
        }
    
        // 获取列表
        http.get('/ssl', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    // 切换每页数量
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

     /** 搜索 */
    onFinishSearch = (data) => {
        this.setState({
            search_instance_platform: data.platform,
            search_instance_account_name: data.account_name,
            search_domain_name: data.domain_name ? data.domain_name : null,
            page: 1
        })
        this.loadData()
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            this.setState({
                search_instance_platform: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const search_option_account = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_account.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    search_option_account: search_option_account
                })
            })
    
        } else {
            this.setState({
                search_option_account: [],
            })
        }
    }

    // 搜索云账户
    onChangeAccountName = (value) => {
        this.setState({
            search_instance_account_name: value ? value : null
        })
    }

    // 证书检测
    onSslCheckBtn = (rowData) => {

        this.setState({loading: true})

        const requestData = {
            operation_type: 'get_ssl_check'
        }

        http.patch('/cloud/domain/' + rowData.id, {params: requestData}).then(response=>{
            this.setState({loading: false})
        })
    }


    downloadTxtFile = (file_name, file_data) => { 
        let element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(file_data));
        element.setAttribute('download', file_name);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
      } 

    // 一键导出
    onexportExcelBtn = (rowData) => {
        this.downloadTxtFile(rowData.domain_name + '.cert', rowData.cert)
        this.downloadTxtFile(rowData.domain_name + '.key', rowData.key)
    }

    render(){
        const { loading, columns, dataSource, page, total, search_option_platform, search_option_account } = this.state
        const rowSelection = {
            onChange: this.onCheckbox
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        var myStyleForm = {marginRight: '10px', marginTop: '5px'}

        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch} size="small">  

                    <Form.Item label="域名" name="domain_name" style={myStyleForm}>
                        <Input placeholder="请输入域名"  />
                    </Form.Item>         

                    <Form.Item label="云平台" name="platform" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangePlatform}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {search_option_platform}
                        </Select>
                    </Form.Item>

                    <Form.Item label="云账户" name="account_name" style={myStyleForm}>
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择云账户"
                            onChange={this.onChangeAccountName}
                            >
                            {search_option_account}
                        </Select>                      
                    </Form.Item>     

                    <Form.Item shouldUpdate={true} style={myStyleForm}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                <div style={myStyle1}><Button type="primary"></Button></div>

                <Table
                    size="small"
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 600, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>
            </Fragment>
        )
    }
}

export default Ssl;